

package com.xgit.iov.common.log.aspect;

import cn.hutool.core.util.ObjectUtil;
import com.xgit.iov.common.core.entity.SysLog;
import com.xgit.iov.common.core.util.SpringContextHolder;
import com.xgit.iov.common.log.event.SysLogEvent;
import com.xgit.iov.common.log.util.SysLogUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * 操作日志使用spring event异步入库
 *
 * @author william
 *
 */
@Aspect
@Slf4j
@Component
public class SysLogAspect {


	@Pointcut("@annotation(com.xgit.iov.common.log.annotation.LogAnnotation)")
	public void logPointCut() {
	}

	/**
	 * 拦截异常操作
	 * @param joinPoint 切点
	 * @param e 异常
	 */
	@SneakyThrows
	@AfterThrowing(value = "logPointCut()", throwing = "e")
	public void doAfterThrowing(JoinPoint joinPoint, Exception e) {
		SysLog logVo = SysLogUtils.getSysLog(joinPoint, e);
		if (ObjectUtil.isNotEmpty(logVo)){
			SpringContextHolder.publishEvent(new SysLogEvent(logVo));
		}
	}

	@Around(value = "logPointCut()")
	@SneakyThrows
	public Object around(ProceedingJoinPoint point) {
		SysLog logVo = SysLogUtils.getSysLog(point, null);
		// 发送异步日志事件
		Long startTime = System.currentTimeMillis();
		Object obj = point.proceed();
		Long endTime = System.currentTimeMillis();
		logVo.setTime(endTime - startTime);
		SpringContextHolder.publishEvent(new SysLogEvent(logVo));
		return obj;
	}

}
